<template>
  <div class="container">
    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" size="small">
          <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="公告标题" clearable />
          </el-form-item>
          <el-form-item label="作者">
          <el-input v-model="searchForm.author" placeholder="作者姓名" clearable />
          </el-form-item>
          <el-form-item label="发布状态">
          <el-select v-model="searchForm.publishStatus" placeholder="选择状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="已发布" value="已发布" />
              <el-option label="暂存" value="暂存" />
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间">
          <el-date-picker v-model="publishTimeRange" type="daterange" range-separator="~" start-placeholder="开始" end-placeholder="结束" value-format="yyyy-MM-dd" clearable />
          </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh-right" size="small" @click="handleReset">重置</el-button>
        </el-form-item>
        </el-form>
      </div>

    <!-- 操作按钮 -->
    <div class="brand-container">
      <div class="title-container">
        <span>公告列表</span>
      </div>
      <div class="button-group-container">
        <el-button type="success" icon="el-icon-download" size="small" @click="handleExport">导出</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="getAnnouncementList">刷新</el-button>
      </div>
      <div class="align-right">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增公告</el-button>
        <el-button type="danger" icon="el-icon-delete" size="small" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">批量删除 ({{ multipleSelection.length }})</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%;"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="handleView(scope.row)">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120" align="center">
          <template slot-scope="scope">
            <el-tag size="small" type="info">{{ scope.row.author }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishStatus" label="发布状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.publishStatus === '已发布' ? 'success' : 'warning'"
              size="small"
            >
              {{ scope.row.publishStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template slot-scope="scope">
            <span class="time-text">
              <i class="el-icon-time" />
              {{ formatDateTime(scope.row.publishTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
          <template slot-scope="scope">
            <span class="time-text">
              <i class="el-icon-date" />
              {{ formatDateTime(scope.row.createdAt) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              v-if="scope.row.publishStatus === '暂存'"
              size="mini"
              type="success"
              @click="handlePublish(scope.row)"
            >
              发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
      <!-- 分页 -->
    <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
    </div>

    <!-- 查看公告详情对话框 -->
    <el-dialog
      title="公告详情"
      :visible.sync="viewDialogVisible"
      width="60%"
      :before-close="handleCloseView"
    >
      <div v-if="currentAnnouncement" class="announcement-detail">
        <div class="detail-header">
          <h2 class="detail-title">{{ currentAnnouncement.title }}</h2>
          <div class="detail-meta">
            <span class="meta-item">
              <i class="el-icon-user" />
              作者：{{ currentAnnouncement.author }}
            </span>
            <span class="meta-item">
              <i class="el-icon-time" />
              发布时间：{{ formatDateTime(currentAnnouncement.publishTime) }}
            </span>
            <span class="meta-item">
              <el-tag
                :type="currentAnnouncement.publishStatus === '已发布' ? 'success' : 'warning'"
                size="small"
              >
                {{ currentAnnouncement.publishStatus }}
              </el-tag>
            </span>
          </div>
        </div>
        <div class="detail-content">
          <div v-html="currentAnnouncement.content" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit(currentAnnouncement)">编辑</el-button>
      </span>
    </el-dialog>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="editDialogVisible"
      width="70%"
      :before-close="handleCloseEdit"
    >
      <el-form ref="announcementForm" :model="announcementForm" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="announcementForm.title" placeholder="请输入公告标题" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="announcementForm.author" placeholder="请输入作者姓名" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="announcementForm.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="正文内容" prop="content">
          <quill-editor
            ref="myQuillEditor"
            v-model="announcementForm.content"
            :options="editorOption"
            style="height: 300px; margin-bottom: 50px;"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAnnouncementList,
  addAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  publishAnnouncement
} from '@/api/announcements'
// import { quillEditor } from 'vue-quill-editor' // 1. 注释或删除同步导入
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { formatTimeRange } from '@/utils/formatDay'

export default {
  name: 'AnnouncementList',
  components: {
    // quillEditor // 2. 从 components 中移除
    // 3. 添加异步组件注册
    quillEditor: () => import('vue-quill-editor').then(m => m.quillEditor)
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        author: '',
        publishStatus: ''
      },
      publishTimeRange: [],

      // 表格数据
      tableData: [],
      loading: false,

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 多选
      multipleSelection: [],

      // 查看对话框
      viewDialogVisible: false,
      currentAnnouncement: null,

      // 编辑对话框
      editDialogVisible: false,
      editDialogTitle: '新增公告',
      saveLoading: false,
      announcementForm: {
        id: null,
        title: '',
        author: '',
        publishStatus: '', // 将由发布时间自动确定
        publishTime: '',
        content: ''
      },

      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'],

            [{ 'header': 1 }, { 'header': 2 }], // custom button values
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
            [{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
            [{ 'direction': 'rtl' }], // text direction

            [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

            [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
            [{ 'font': [] }],
            [{ 'align': [] }],

            ['clean'], // remove formatting button
            ['link', 'image', 'video'] // link and image, video
          ]
        },
        placeholder: '请输入公告正文内容...'
      },
      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 1, max: 255, message: '标题长度在 1 到 255 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' },
          { min: 1, max: 50, message: '作者姓名长度在 1 到 50 个字符', trigger: 'blur' }
        ],

        publishTime: [
          { required: true, message: '请选择发布时间', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入正文内容', trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    this.getAnnouncementList()
  },

  methods: {
    // 获取公告列表
    async getAnnouncementList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          title: this.searchForm.title,
          author: this.searchForm.author,
          publishStatus: this.searchForm.publishStatus
        }

        // 处理时间范围
        if (this.publishTimeRange && this.publishTimeRange.length === 2) {
          const { startTime, endTime } = formatTimeRange(this.publishTimeRange)
          params.startTime = startTime
          params.endTime = endTime
        }

        // 调用API接口
        const response = await getAnnouncementList(params)

        if (response.data.code === 1) {
          this.tableData = response.data.data.rows || []
          this.total = response.data.data.total || 0
        } else {
          this.$message.error(response.data.msg || '获取公告列表失败')
        }
      } catch (error) {
        this.$message.error('获取公告列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // API调用
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          title: this.searchForm.title,
          author: this.searchForm.author,
          publishStatus: this.searchForm.publishStatus,
          startTime: this.publishTimeRange && this.publishTimeRange[0] ? this.publishTimeRange[0] : null,
          endTime: this.publishTimeRange && this.publishTimeRange[1] ? this.publishTimeRange[1] : null
        }

        const response = await this.$http.get('/announcements/page', { params })

        if (response.data.code === 200) {
          this.tableData = response.data.data.rows
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getAnnouncementList()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        title: '',
        author: '',
        publishStatus: ''
      }
      this.publishTimeRange = []
      this.currentPage = 1
      this.getAnnouncementList()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getAnnouncementList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.getAnnouncementList()
    },

    // 多选变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 新增公告
    handleAdd() {
      this.editDialogTitle = '新增公告'
      this.announcementForm = {
        id: null,
        title: '',
        author: '',
        publishStatus: '暂存',
        publishTime: '',
        content: ''
      }
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.announcementForm.clearValidate()
      })
    },

    // 编辑公告
    handleEdit(row) {
      this.editDialogTitle = '编辑公告'
      this.announcementForm = {
        id: row.id,
        title: row.title,
        author: row.author,
        publishStatus: row.publishStatus,
        publishTime: row.publishTime,
        content: row.content
      }
      this.editDialogVisible = true
      this.viewDialogVisible = false
      this.$nextTick(() => {
        this.$refs.announcementForm.clearValidate()
      })
    },

    // 查看公告详情
    handleView(row) {
      this.currentAnnouncement = row
      this.viewDialogVisible = true
    },

    // 删除公告
    handleDelete(row) {
      this.$confirm(`此操作将永久删除公告"${row.title}", 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await deleteAnnouncement(row.id)
          if (response.data.code === 1) {
            this.$message.success('删除成功!')
            this.getAnnouncementList()
          } else {
            this.$message.error(response.data.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error(error)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的公告')
        return
      }

      this.$confirm(`此操作将永久删除选中的${this.multipleSelection.length}条公告, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const ids = this.multipleSelection.map(item => item.id)
          const response = await deleteAnnouncement(ids)
          if (response.data.code === 1) {
            this.$message.success('批量删除成功!')
            this.multipleSelection = []
            this.getAnnouncementList()
          } else {
            this.$message.error(response.data.msg || '批量删除失败')
          }
        } catch (error) {
          this.$message.error('批量删除失败')
          console.error(error)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 导出数据
    handleExport() {
      this.$message.info('导出功能开发中...')
    },

    // 保存公告
    async handleSave() {
      // 判断发布时间
      if (this.announcementForm.publishTime) {
        const now = new Date()
        const publishTime = new Date(this.announcementForm.publishTime)
        if (publishTime <= now) {
          this.announcementForm.publishStatus = '已发布'
        } else {
          this.announcementForm.publishStatus = '暂存'
        }
      } else {
        // 如果没有选择发布时间，默认为暂存 (或者你可以根据业务需求设置为立即发布)
        this.announcementForm.publishStatus = '暂存'
      }

      this.$refs.announcementForm.validate(async(valid) => {
        if (valid) {
          this.saveLoading = true

          try {
            let response
            if (this.announcementForm.id) {
              // 编辑公告
              response = await updateAnnouncement(this.announcementForm)
            } else {
              // 新增公告
              response = await addAnnouncement(this.announcementForm)
            }

            if (response.data.code === 1) {
              this.editDialogVisible = false
              if (this.announcementForm.id) {
                this.$message.success('编辑成功!')
              } else {
                this.$message.success('新增成功!')
              }
              this.getAnnouncementList()
            } else {
              this.$message.error(response.data.msg || '保存失败')
            }
          } catch (error) {
            this.$message.error('保存失败')
            console.error(error)
          } finally {
            this.saveLoading = false
          }
        } else {
          return false
        }
      })
    },

    // 关闭查看对话框
    handleCloseView() {
      this.viewDialogVisible = false
      this.currentAnnouncement = null
    },

    // 关闭编辑对话框
    handleCloseEdit() {
      this.editDialogVisible = false
      this.$refs.announcementForm.resetFields()
    },

    // 立即发布
    handlePublish(row) {
      this.$confirm(`确认立即发布公告"${row.title}"?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async() => {
        try {
          const response = await publishAnnouncement(row.id)
          if (response.data.code === 1) {
            this.$message.success('发布成功!')
            this.getAnnouncementList()
          } else {
            this.$message.error(response.data.msg || '发布失败')
          }
        } catch (error) {
          this.$message.error('发布失败')
          console.error(error)
        }
      }).catch(() => {
        this.$message.info('已取消发布')
      })
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}
.search-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  row-gap: 10px;
  align-items: center;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
.brand-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.title-container {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}
.button-group-container {
  display: flex;
  gap: 10px;
  flex-grow: 1;
  margin-left: 20px;
}
.align-right {
  margin-left: auto;
}
.table-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}
.pagination-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 20px;
  text-align: right;
}
.time-text {
  color: #606266;
}
.time-text i {
  margin-right: 5px;
}
.announcement-detail .detail-header {
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
  margin-bottom: 20px;
}
.announcement-detail .detail-title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 10px;
}
.announcement-detail .detail-meta {
  display: flex;
  gap: 20px;
  color: #909399;
  font-size: 14px;
}
.announcement-detail .detail-content {
  line-height: 1.8;
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .container,
body.dark-theme .search-container,
body.dark-theme .brand-container,
body.dark-theme .table-container,
body.dark-theme .pagination-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
  }
body.dark-theme .el-table,
body.dark-theme .el-table th,
body.dark-theme .el-table td {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-table th {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
  }
body.dark-theme .el-table td {
  border-bottom: 1px solid #444 !important;
  }
body.dark-theme .el-table .el-table__row:hover {
  background-color: #2b2b2b !important;
  }
body.dark-theme .el-input__inner,
body.dark-theme .el-select .el-input__inner {
  background-color: #232323 !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #fff !important;
}
body.dark-theme .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}
body.dark-theme .el-button--info {
  background-color: #909399 !important;
  border-color: #909399 !important;
  color: #fff !important;
}
body.dark-theme .el-button--warning {
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff !important;
}
body.dark-theme .el-pagination,
body.dark-theme .el-pagination__total,
body.dark-theme .el-pagination__jump,
body.dark-theme .el-pagination__editor,
body.dark-theme .el-pagination__sizes,
body.dark-theme .el-pagination__sizes .el-input__inner {
  background-color: #1f1f1f !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-dialog {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-dialog__header {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-dialog__title {
  color: #fff !important;
}
body.dark-theme .el-dialog__body {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-form-item__label {
  color: #fff !important;
}
body.dark-theme .el-select-dropdown {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item.selected {
  background-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item:hover {
  background-color: #2b2b2b !important;
  color: #fff !important;
}
body.dark-theme .el-tag.el-tag--success {
  background-color: #1f1f1f !important;
  color: #67c23a !important;
  border-color: #67c23a !important;
}
body.dark-theme .el-tag.el-tag--warning {
  background-color: #1f1f1f !important;
  color: #e6a23c !important;
  border-color: #e6a23c !important;
}
body.dark-theme .el-tag.el-tag--info {
  background-color: #1f1f1f !important;
  color: #909399 !important;
  border-color: #909399 !important;
}
body.dark-theme .time-text {
  color: #bbb !important;
}
body.dark-theme .announcement-detail .detail-header {
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .announcement-detail .detail-title {
  color: #fff !important;
}
body.dark-theme .announcement-detail .detail-meta {
  color: #bbb !important;
}
body.dark-theme .announcement-detail .detail-content {
  color: #fff !important;
}
</style>
